import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:yysk_app/net/api/api_url.dart';
import 'package:yysk_app/net/http.dart';
import 'package:yysk_app/routes/global_controller.dart';
import 'package:yysk_app/utils/colors.dart';
import 'package:yysk_app/utils/helper.dart';
import 'package:yysk_app/utils/js_tool.dart';
import 'package:yysk_app/widget/app_bar_back_widget.dart';
import 'package:yysk_app/widget/button_widget.dart';
import 'package:yysk_app/widget/custom_app_bar2.dart';
import 'package:yysk_app/widget/image_asset_widget.dart';
import 'package:yysk_app/widget/input_widget.dart';
import 'package:yysk_app/widget/verification_code_widet.dart';
import 'package:oktoast/oktoast.dart';

class ForgotPasswordPage extends StatefulWidget {
  static const path = '/forgotPasswordPage';
  const ForgotPasswordPage({super.key});
  @override
  State<StatefulWidget> createState() => _ForgotPasswordPage();
}

class _ForgotPasswordPage extends State<ForgotPasswordPage> {
  final TextEditingController phoneController = TextEditingController();
  final TextEditingController onePwdontroller = TextEditingController();
  final TextEditingController twoPwdController = TextEditingController();
  final GlobalController globalController = Get.find();
  final registerEnable = false.obs;
  String pwdErrorOne = '';
  String pwdErrorTwo = '';
  String? codes;
  int? smsId;
  String onePwd = '';
  String twoPwd = '';

  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    double top = MediaQuery.of(context).padding.top;

    return Scaffold(
      backgroundColor: AppColors.backgroundColorBlack,
      body: SingleChildScrollView(
        child: Stack(
          children: [
            Positioned.fill(
              top: 0.px,
              left: 0,
              child: ImageAssetWidget(
                imageUrl: 'static/images/bg2.png',
                width: 375.px,
                height: 812.px,
                fit: BoxFit.fitWidth,
                alignment: Alignment.topCenter,
              ),
            ),

            Column(
              children: [
                SizedBox(height: top),
                CustomAppBar2(title: '', context: context),
                Padding(
                  padding: EdgeInsets.fromLTRB(24.px, 38.px, 24.px, 0.px),
                  child: Column(
                    children: [
                      Row(
                        children: [
                          hiSpace(width: 8.px),
                          Text(
                            '设置登录密码',
                            style: TextStyle(
                              fontSize: 24.px,
                              color: AppColors.fontColor,
                              fontWeight: FontWeight.w500,
                            ),
                          ),
                        ],
                      ),
                      hiSpace(height: 71.px),
                      InputWidget(
                        disabled: true,
                        hint: '${globalController.user.value?.userTel}',
                        backgroundColor: AppColors.backgroundColorBlackLight,
                        buttonRadio: 24,
                        inputType: TextInputType.number,
                        controller: phoneController,
                        onChanged: (value) {},
                      ),
                      hiSpace(height: 12.px),

                      VerificationCodeWidet(
                        initialCount: 60,
                        buttonRadio: 24,
                        phoneNumber: '${globalController.user.value?.userTel}',
                        type: VerificationCodeType.RESET_PASSWORD,
                        onChanged: ({String? code, int? msgId}) {
                          if (code != null && code != '') {
                            changeValue(code, 'codes');
                          }
                          changeValue(msgId, 'smsId');
                        },
                      ),
                      hiSpace(height: 12.px),
                      InputWidget(
                        hint: '支持8-18位，由数字和字母组成',
                        backgroundColor: AppColors.backgroundColorBlackLight,
                        buttonRadio: 24,
                        obscureText: true,
                        visible: true,
                        // errorText: pwdErrorOne,
                        controller: onePwdontroller,
                        onChanged: (value) {
                          if (value.length < 19) {
                            changeValue(
                              value.length > 18
                                  ? value.substring(0, 18)
                                  : value,
                              'onePwd',
                            );
                          } else {
                            //或者输入上一次数据
                            onePwdontroller.value = TextEditingValue(
                              text: onePwd, // 截断到 11 位
                              selection: TextSelection.collapsed(
                                offset: onePwd.length,
                              ), // 光标移动到末尾
                            );
                          }
                        },
                      ),
                      hiSpace(height: 12.px),

                      InputWidget(
                        hint: '再次确认密码',
                        backgroundColor: AppColors.backgroundColorBlackLight,
                        buttonRadio: 24,
                        obscureText: true,
                        visible: true,
                        // errorText: pwdErrorTwo,
                        controller: twoPwdController,
                        onChanged: (value) {
                          if (value.length < 19) {
                            changeValue(
                              value.length > 18
                                  ? value.substring(0, 18)
                                  : value,
                              'twoPwd',
                            );
                          } else {
                            //或者输入上一次数据
                            twoPwdController.value = TextEditingValue(
                              text: twoPwd, // 截断到 11 位
                              selection: TextSelection.collapsed(
                                offset: twoPwd.length,
                              ), // 光标移动到末尾
                            );
                          }
                        },
                      ),
                    ],
                  ),
                ),
                hiSpace(height: 64.px),
                ButtonWidget(
                  height: 47.px,
                  width: 327.px,
                  fontSize: 16.px,
                  fontWeight: FontWeight.w500,
                  label: '确定',
                  onPressed: () {
                    if (onePwd != twoPwd) {
                      showToast('两次密码输入不一致');
                    } else {
                      _submit();
                    }
                  },
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }

  void changeValue(dynamic value, String type) {
    if (type == 'onePwd') {
      setState(() {
        onePwd = value;
      });
      _validatePasswordOne(value);
    } else if (type == 'twoPwd') {
      setState(() {
        twoPwd = value;
      });
      _validatePasswordTwo(value);
    } else if (type == 'codes') {
      setState(() {
        codes = value;
      });
    } else if (type == 'smsId') {
      setState(() {
        smsId = value;
      });
    }
  }

  void _validatePasswordOne(String password) {
    // 定义正则表达式，要求密码同时包含数字、字母及特殊字符，且长度至少为8个字符
    RegExp regex = RegExp(r'^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{8,18}$');

    // 使用正则表达式进行匹配
    if (!regex.hasMatch(password)) {
      // 如果密码不符合规则，返回一个错误消息

      pwdErrorOne = '登录密码8-18位数，包含字母和数字，不支持特殊字符';
      return;
    }

    pwdErrorOne = '';
  }

  void _validatePasswordTwo(String password) {
    // 定义正则表达式，要求密码同时包含数字、字母及特殊字符，且长度至少为8个字符
    RegExp regex = RegExp(r'^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{8,18}$');

    // 使用正则表达式进行匹配
    if (!regex.hasMatch(password)) {
      // 如果密码不符合规则，返回一个错误消息

      pwdErrorTwo = '登录密码8-18位数，包含字母和数字，不支持特殊字符';
      return;
    }

    pwdErrorTwo = '';
  }

  void _submit() {
    if (pwdErrorOne != '') {
      showToast(pwdErrorOne);
      return;
    }
    if (pwdErrorTwo != '') {
      showToast(pwdErrorTwo);
      return;
    }

    http.netFetch(
      ApiUrl.forgetUserPassword,
      params: {
        "codes": codes,
        "smsId": smsId,
        "onePwd": onePwd,
        "twoPwd": twoPwd,
        "userAccount": '${globalController.user.value?.userTel}',
      },
      success: (data) {
        showToast('修改成功');
        Get.back();
      },
    );
  }
}
